/*
 * Copyright 2006 Matt Jensen
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.jtell.xdoclet;

import org.apache.commons.lang.StringUtils;
import xdoclet.XDocletException;
import xdoclet.XDocletTagSupport;
import xjavadoc.XMethod;
import xjavadoc.XParameter;
import xjavadoc.XTag;

import java.util.List;

/**
 * <p>
 * <code>JTellTagsHandler</code> is an extension of {@link XDocletTagSupport} which implements custom tag
 * functionality that is required in the generation of the listener metadata template. 
 * </p>
 */
public class JTellTagsHandler extends XDocletTagSupport
{
    /**
     * <p>
     * Construct a {@link JTellTagsHandler} instance.
     * </p>
     */
    public JTellTagsHandler()
    {
        super();
    }

    /**
     * <p>
     * Determine whether the current class has at least one annotated event listener method.
     * </p>
     *
     * @param template the inner template text.
     * @throws XDocletException on error processing the inner template.
     */
    public void ifHasEventListenerMethod(final String template) throws XDocletException
    {
        // Loop over methods.
        @SuppressWarnings("unchecked")
        final List<XMethod> methods = getCurrentClass().getMethods();
        for (final XMethod method : methods)
        {
            // Check the next method for an appropriate annotation.
            if (method.getDoc().hasTag(EVENT_LISTENER_TAG))
            {
                // Found the first listener method. Process the inner template and return.
                generate(template);
                break;
            }
        }
    }

    /**
     * <p>
     * Get the event class for the current listener method.  The <code>currentMethod</code> must have been found to have
     * the appropriate annotation prior to invocation of this method.
     * </p>
     * <p>
     * This method first looks for an <code>event-class</code> parameter on the <code>event.listener</code> tag; if
     * found, that class is used. Otherwise it uses the type of the first method parameter.
     * </p>
     *
     * @return {@link String} event class name.
     */
    public String eventClass() throws XDocletException
    {
        // Get the event listener tag.
        final XMethod method = getCurrentMethod();
        @SuppressWarnings("unchecked")
        final List<XTag> tags = method.getDoc().getTags(EVENT_LISTENER_TAG);
        if (tags.size() > 1)
        {
            throw new XDocletException(String.format("Method %s has more than one %s tag.",
                    method.getNameWithSignature(true), EVENT_LISTENER_TAG));
        }

        // Check for an event-class attribute.
        final XTag tag = tags.get(0);
        final String eventClassValue = tag.getAttributeValue(EVENT_CLASS_ATTRIBUTE);
        final String result;
        if (!StringUtils.isBlank(eventClassValue))
        {
            // Use the value from the event-class parameter.
            result = eventClassValue;
        }
        else
        {
            // No event class parameter; we will have to examine the method signature.
            final List parameters = method.getParameters();
            if (parameters.isEmpty())
            {
                throw new XDocletException(String.format(
                        "Method %s must either take at least one parameter or the %s tag must provide an %s attribute.",
                        method.getNameWithSignature(true), EVENT_LISTENER_TAG, EVENT_CLASS_ATTRIBUTE));
            }

            // Use the type of the first parameter.
            final XParameter parameter = (XParameter) parameters.get(0);
            result = parameter.getType().getQualifiedName();
        }
        return result;
    }

    /**
     * <p>
     * Get a string representing the signature of the current method (including its name, but not its return type.)
     * </p>
     *
     * @return {@link String} method signature.
     */
    public String methodSignature()
    {
        return XJavaDocUtils.getMethodSignature(getCurrentMethod());
    }

    /**
     * <p>
     * Get the source class for the current listener method.
     * </p>
     * <p>
     * This method looks for a <code>source-class</code> parameter on the <code>event.listener</code> tag; if found,
     * that class is used. Otherwise <code>java.lang.Object</code> is used. 
     * </p>
     *
     * @return {@link String} source class name.
     */
    public String sourceClass()
    {
        // First look for the source-class parameter.
        final XMethod method = getCurrentMethod();
        final XTag tag = method.getDoc().getTag(EVENT_LISTENER_TAG);
        final String sourceClassValue = tag.getAttributeValue(SOURCE_CLASS_ATTRIBUTE);
        final String result;
        if (!StringUtils.isBlank(sourceClassValue))
        {
            // Use the value from the source-class parameter.
            result = sourceClassValue;
        }
        else
        {
            // Otherwise return the default.
            result = DEFAULT_SOURCE_CLASS;
        }
        return result;
    }

    /**
     * <p>
     * Default source class to return from {@link #sourceClass()} if none is annotated.
     * </p>
     */
    private static final String DEFAULT_SOURCE_CLASS = Object.class.getName();

    /**
     * <p>
     * Name of the event class attribute.
     * </p>
     */
    private static final String EVENT_CLASS_ATTRIBUTE = "class";

    /**
     * <p>
     * Name of the doclet tag with which event listener methods are annotated.
     * </p>
     */
    private static final String EVENT_LISTENER_TAG = "listener.event";

    /**
     * <p>
     * Name of the source class attribute.
     * </p>
     */
    private static final String SOURCE_CLASS_ATTRIBUTE = "source-class";
}
